﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Common;
using Models;
using DbControl;
using System.Configuration;
using System.Xml.Linq;

namespace CentralMonitoring
{
    /// <summary>
    /// 设备信息管理窗体
    /// </summary>
    public partial class DevicesFrm : Form
    {
        public DevicesFrm()
        {
            InitializeComponent();
        }
        private int m_currentNodeTag;
        #region treeview
        private void InitTree()
        {
            this.treeView1.Nodes.Clear();
            DataTable dt = OprDevice.GetdevicesTree(); 
            if (dt != null && dt.Rows.Count > 0)
            {
                DataView dv = dt.DefaultView;
                dv.Sort = "parentid ASC";
                DataRowView[] arrDRV = dv.FindRows("0");
                if (arrDRV.Length == 0)
                    return;
                TreeNode tnNew = null;
                treeView1.BeginUpdate();
                foreach (DataRowView drv in arrDRV)
                {
                    tnNew = this.treeView1.Nodes.Add(drv["device_name"].ToString());
                    tnNew.Tag = drv.Row["id"];
                    CreateTreeNode(ref tnNew, dv);
                }
                treeView1.EndUpdate();
                treeView1.ExpandAll();
            }
        }
        private void CreateTreeNode(ref TreeNode tnParent, DataView dv)
        {
            DataRowView[] arrDrv = dv.FindRows(tnParent.Tag);
            if (arrDrv.Length == 0)
                return;
            TreeNode tnNew = null;
            foreach (DataRowView drv in arrDrv)
            {
                tnNew = tnParent.Nodes.Add(drv.Row["device_name"].ToString());
                tnNew.Tag = drv.Row["ID"].ToString();
                CreateTreeNode(ref tnNew, dv);

            }
        }
        private void treeView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Point clickPoint = new Point(e.X, e.Y);
                TreeNode currentNode = treeView1.GetNodeAt(clickPoint);
                if (currentNode != null)
                {
                    currentNode.ContextMenuStrip = this.contextMenuStrip1;
                    treeView1.SelectedNode = currentNode;
                }
                else
                {
                    this.treeView1.ContextMenuStrip = this.contextMenuStrip2;
                    treeView1.SelectedNode = null;
                }
            }

        }
        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            int nodeId;
            if (e.Node.Nodes.Count > 0)
            {
                e.Node.Expand();                
                nodeId = int.Parse(e.Node.Tag.ToString());
                treeView1.SelectedNode = e.Node;
                textBoxDevice.Text = e.Node.Text;
                RefreshGrid(nodeId,true);
            }
            else
            {
                nodeId=int.Parse(e.Node.Tag.ToString());
                treeView1.SelectedNode = e.Node;
                textBoxDevice.Text = e.Node.Text;
                RefreshGrid(nodeId);
            }
            m_currentNodeTag = nodeId;


        }
        private void 新建ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeviceEdit deviceEdit = new DeviceEdit();
            deviceEdit.m_ParentId=int.Parse(treeView1.SelectedNode.Tag.ToString());
            deviceEdit.m_type = OprType.Add;
            string name=treeView1.SelectedNode.Text.ToString();
            if (deviceEdit.ShowDialog() == DialogResult.OK)
            {
                InitTree();
                RefreshGrid(name);
            }
        }

        private void 修改ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeviceEdit deviceEdit=new DeviceEdit();
            deviceEdit.m_Id = int.Parse(treeView1.SelectedNode.Tag.ToString());
            deviceEdit.m_beforName=this.treeView1.SelectedNode.Text.ToString();
            deviceEdit.m_type = OprType.Modify;            
            if (deviceEdit.ShowDialog() == DialogResult.OK)
            {
                
                int nodeID= int.Parse(treeView1.SelectedNode.Tag.ToString());
                RefreshGrid(nodeID);
                InitTree();
            }
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode == null)
            {
                MessageBox.Show("请选择要删除的设备！");
                return;
            }
            if (treeView1.SelectedNode.Nodes.Count > 0)
            {
                if (MessageBox.Show("此设备下属所有信息都将删除，确定要删除该信息吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                {
                    return;
                }

            }
            else
            {
                if (MessageBox.Show("确定要删除该信息吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                {
                    return;
                }
            }

            //选中节点的id，也是其子节点的parentId
            int id = int.Parse(treeView1.SelectedNode.Tag.ToString());
            nodeDelete(id);//递归删除数据表中的数据
            treeView1.SelectedNode.Remove();//删除控件中的节点
            RefreshGrid(id);
        }
        private void nodeDelete(int id)
        {            
            DataTable dt = OprDevice.GetdevicesByParentId(id);
            if (dt.Rows.Count > 0)
            {
                //有子节点
                foreach (DataRow dr in dt.Rows)
                {
                    //先删除父节点                    
                    if (OprDevice.DeleteById(id)>0)
                    {
                        int id1 = (int)dr["id"];
                        nodeDelete(id1);
                    }
                }
            }
            else
            {
                //无子节点
                OprDevice.DeleteById(id);
            }
        }
        /// <summary>
        /// 新建父节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 新建ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            DeviceEdit dlg = new DeviceEdit();
            dlg.m_ParentId= 0;
            dlg.m_type = OprType.Add;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                InitTree();
            }
        }
        #endregion

        private void DevicesFrm_Load(object sender, EventArgs e)
        {
            this.StatusLabel0.Text = string.Format("系统时间：{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            InitTree();
            RefreshGrid("");
            this.WindowState = FormWindowState.Maximized;
        }
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            string name = treeView1.SelectedNode.Text.ToString();
            if (MessageBox.Show(string.Format("确定要在 {0} 下创建子设备信息吗？",name), "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
            {
                return;
            }
            DeviceEdit deviceEdit = new DeviceEdit();
            deviceEdit.m_ParentId = int.Parse(treeView1.SelectedNode.Tag.ToString());
            deviceEdit.m_type = OprType.Add;           

            if (deviceEdit.ShowDialog() == DialogResult.OK)
            {
                InitTree();
                RefreshGrid(name);
            }
        }

        private void buttonUpdate_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)//dataGridView1.Rows.Count
            {
                int nID = (int)dataGridView1.SelectedRows[0].Cells["id"].Value;//(int)dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["Id"].Value;
                DeviceEdit dlg = new DeviceEdit();
                dlg.m_type =OprType.Modify;
                dlg.m_Id = nID;
                dlg.m_beforName = dataGridView1.SelectedRows[0].Cells["device_name"].Value.ToString();
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    RefreshGrid("");                    
                    //int nodeID = int.Parse(treeView1.SelectedNode.Tag.ToString());
                    //string nodeName = treeView1.SelectedNode.Text;
                    //RefreshGrid(nodeID);
                    InitTree();
                    //treeSetView.SetSelectTreeView(treeView1, nodeName);
                }            

            }
        }

        private void buttonDel_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode == null)
            {
                MessageBox.Show("请选择要删除的设备！");
                return;
            }
            if (treeView1.SelectedNode.Nodes.Count > 0)
            {
                if (MessageBox.Show("此设备下属所有信息都将删除，确定要删除该信息吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                {
                    return;
                }
                //选中节点的id，也是其子节点的parentId
                int id = int.Parse(treeView1.SelectedNode.Tag.ToString());
                nodeDelete(id);//递归删除数据表中的数据
                treeView1.SelectedNode.Remove();//删除控件中的节点
                RefreshGrid(id);

            }
            else
            {
                if (MessageBox.Show("确定要删除该信息吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                {
                    return;
                }
                int nId = (int)dataGridView1.SelectedRows[0].Cells["Id"].Value;
                if (OprDevice.DeleteById(nId) > 0)
                {
                    int nodeID = int.Parse(treeView1.SelectedNode.Tag.ToString());
                    RefreshGrid(nodeID);
                    InitTree();                  
                }                    
                else
                    MessageBox.Show("删除失败！");

            }

           
        }

        #region dataGridView1
        private void RefreshGrid(int parentid,bool isParent=false)
        {
            DataTable dataTable = new DataTable();
            dataTable = OprDevice.GetdevicesByTreeNode(parentid,isParent);
            RefreshGrid(dataTable);
        }
        private void RefreshGrid(string name)
        {          
            DataTable dt = OprDevice.GetdevicesByName(name);
            if (dt != null)
            {
                RefreshGrid(dt);
            }

        }
        private void RefreshGrid(DataTable dt)
        {          
            if (dt != null)
            {
                this.dataGridView1.DataSource = dt;
                dataGridView1.Columns["id"].Visible = false;
                dataGridView1.Columns["parentid"].Visible = false;
                dataGridView1.Columns["device_name"].HeaderText = "设备名称";
                dataGridView1.Columns["device_code"].HeaderText = "识别码";
                dataGridView1.Columns["device_position"].HeaderText = "安装位置";
                dataGridView1.Columns["device_type"].HeaderText = "规格型号";
                dataGridView1.Columns["device_factory"].HeaderText = "设备厂家";
                dataGridView1.Columns["install_time"].HeaderText = "安装时间";
                dataGridView1.Columns["create_time"].Visible = false;
                dataGridView1.Columns["device_mode"].HeaderText = "设备分类";
                dataGridView1.Columns["oil_id"].Visible = false;
                dataGridView1.Columns["warn_id"].Visible = false;
                dataGridView1.Columns["parameter_id"].Visible = false;
                dataGridView1.Columns["sensor_id"].Visible = false;
                dataGridView1.Columns["Flag"].HeaderText = "状态";
                dgSetView.SetFormatDataGridView(dataGridView1);
            }

        }
        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e == null || e.Value == null || !(sender is DataGridView))
            {
                return;
            }
            DataGridView dgv = (DataGridView)sender;
            object originalValue = e.Value;
            int dValue = 0;
            if (dgv.Columns[e.ColumnIndex].DataPropertyName == "flag")
            {
                if (e.Value != null && int.TryParse(e.Value.ToString(), out dValue))
                    e.Value = dValue > 0 ? "启用" : "禁用";
            }
        }
        #endregion
        private void buttonParaSet_Click(object sender, EventArgs e)
        {
            DeviceConfigFrm dlg = new DeviceConfigFrm();
            dlg.ShowDialog();
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void buttonFind_Click(object sender, EventArgs e)
        {            
            //if(!string.IsNullOrEmpty(textBoxDevice.Text))
                RefreshGrid(textBoxDevice.Text);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            StatusLabel0.Text = string.Format("系统时间：{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        }

        private void toolStripStatusLabel1_Click(object sender, EventArgs e)
        {
            ServerEdit dlg=new ServerEdit();
            dlg.ShowDialog();
        }

       
    }
}
